# 将PDF里的图片导出到文件夹
import fitz as mupdf
import os
# PDF在电脑里的路径
pdf_file = "E:/123.pdf"
# 导出的文件夹路径和名称
output_dir = "E:/extracted_images"

def extract_images_from_pdf(pdf_path, output_folder):
    # 若输出文件夹不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    try:
        # 尝试不同方式打开 PDF 文件
        try:
            pdf_document = mupdf.open(pdf_path)
        except AttributeError:
            pdf_document = mupdf.Document(pdf_path)

        for page_num in range(len(pdf_document)):
            page = pdf_document.load_page(page_num)
            image_list = page.get_images(full=True)

            for image_index, img in enumerate(image_list, start=1):
                xref = img[0]
                base_image = pdf_document.extract_image(xref)
                image_bytes = base_image["image"]
                image_ext = base_image["ext"]
                if image_index == 2:
                    # 设置图片名称
                    image_name = f"{page_num + 1}.{image_ext}"
                    image_path = os.path.join(output_folder, image_name)

                    with open(image_path, "wb") as image_file:
                        image_file.write(image_bytes)
                    print(f"图片: {image_name} 已保存到 {output_folder}")

        pdf_document.close()
    except Exception as e:
        print(f"出现错误: {e}")


if __name__ == "__main__":
    extract_images_from_pdf(pdf_file, output_dir)